var url = 'http://47.105.118.98:9013'
layui.use(['form', 'layer', 'laydate', 'table'], function () {
    var form = layui.form,
        layer = layui.layer,
        $ = layui.jquery,
        laydate = layui.laydate,
        table = layui.table;
    //新闻列表
    option = {
        elem: '#demo',
        id: 'demo',
        //    url: url + '/dutyroster/querydutyroster',
        page: true,
        // height: "full-140",
        limit: 7,
        where: {
            keyWord: ''
        },
        text: {
            none: '暂无相关数据' //默认：无数据
        },
        request: {
            pageName: "currentPage", //页码的参数名称，
            limitName: "size", //每页数据量的参数名，
        },
        headers: {
            token: localStorage.getItem('token')
        },
        parseData: function (res) { //res 即为原始返回的数据
            // console.log(res)
            return {
                "code": 0, //解析接口状态
                "msg": res.message, //解析提示文本
                "count": res.data.count, //解析数据长度
                "data": res.data.dutyrosterList //解析数据列表
            };

        },
        limits: [7, 9, 11, 13],
        data: [
            {
                "workingDate": '2019-09-09',
                "caseDuty": '234'
            }, {
                "workingDate": '2019-09-09',
                "caseDuty": '234'
            }, {
                "workingDate": '2019-09-09',
                "caseDuty": '234'
            }, {
                "workingDate": '2019-09-09',
                "caseDuty": '234'
            }
        ],
        cols: [
            [{
                type: "checkbox",
                fixed: "left"
            },
            {
                field: 'workingDate',
                title: '日期',
                align: 'center'
            },
            {
                field: 'caseDuty',
                title: '文件名',
                align: 'center'
            },
            // {
            // 	field: 'communityDuty',
            // 	title: '社区值班',
            // 	align: 'center'
            // },
            {
                title: '操作',
                templet: '#newsListBar',
                fixed: "right",
                align: "center"
            }
            ]
        ]
    };
    laydate.render({
        elem: '#changeDate'
    });
    var tableIns = table.render(option);

    //添加值班表格内容
    form.on('submit(add)', function (data) {
        var data1 = {};
        data1.caseDuty = data.field.caseDuty;
        data1.communityDuty = data.field.communityDuty;
        data1.workingDate = data.field.workingDate;
        console.log(data1)
        $.ajax({
            url: url + "/dutyroster/addorupdate",
            method: "post",
            data: data1,
            headers: {
                token: localStorage.getItem('token')
            },
            success: function (data) {
                // console.log(data)
                if (data.code === 1) {
                    layer.closeAll();
                    tableIns.reload();
                    layer.msg("添加成功！")
                } else {
                    layer.msg(data.msg)
                }
            }

        })
    });


    // 根据选中行删除选中内容
    $("#delete_Btn").on("click", function () {
        var checkStatus = table.checkStatus('demo'); //即为基础参数 id 对应的值
        var data1 = '';

        checkStatus.data.forEach((item) => {
            data1 += item.id + ',';
        });
        data1 = data1.substr(0, data1.length - 1)
        // console.log(data1)
        if (data1.length !== 0) {
            $.ajax({
                url: url + "/dutyroster/deletedutyroster",
                method: "post",
                data: {
                    ids: data1
                },
                headers: {
                    token: localStorage.getItem('token')
                },
                success: function (data) {
                    // console.log(data)
                    if (data.code === 1) {
                        tableIns.reload();
                        layer.msg('删除成功！')

                    } else {
                        layer.msg(data.message)
                    }

                },
                error: function (err) {
                    layer.msg('删除失败！')
                }
            })
        } else {
            layer.msg("请先选择需要删除的内容！", {
                icon: 2
            });
        }
    })
    // 上传弹窗接口
    $("#shangchuan").on("click", function uploadFile() {
        layui.use('layer', function () {
            var layer = layui.layer;
            layer.open({
                type: 1,
                area: ["600px", "450px"],
                title: "上传文件",
                content: $("#file_upload_div")
            })
        });

    }),
        layui.use('upload', function () {
            laydate.render({
                elem: '#date',
                trigger: 'click'
            });
            var upload = layui.upload;
            let cookies = document.cookie.split(',');
            let pattern = /csrftoken=(.*)/m;
            let csrf;
            for (let j = 0; j < cookies.length; j++) {
                if (pattern.test(cookies[j])) {
                    csrf = pattern.exec(cookies[j])[1];
                }
            }
            //执行实例
            var url = "http://47.105.118.98:9013";
            var uploadInst = upload.render({

                elem: '#test10' //绑定元素
                , headers: {
                    "X-CSRFToken": csrf
                },
                xhr: function () {
                    var newXhr = i.ajaxSettings.xhr();
                    // 给xhr的upload添加progress的监听
                    newXhr.upload.addEventListener('progress', function (e) {
                        var percent = Math.floor(e.loaded / e.total * 100); //计算出进度
                        typeof l.progress === 'function' && l.progress(e, percent); // 传递给upload的progress回调
                    });
                    return newXhr;
                }
                ,
                progress: function (e, percent) {
                    console.log("进度：" + percent + '%');
                    element.progress('progressBar', percent + '%');
                }
                ,
                exts: 'xls|xlsx|csv|zip|pdf|doc|docx|png|jpeg|jpg|gif|txt'// 设置允许上传的格式
                , auto: false
                , bindAction: "#upload"
                , url: url + '/document/upfile' //上传接口
                , choose: function (obj) {
                    obj.preview(function (index, file, result) {
                        document.getElementById("file_name").value = file.name;
                    })
                }
                , done: function (res) {
                    document.getElementsByClassName("layui-layer-close")[0].click()
                    layer.msg("上传成功")
                }
                , error: function () {
                    layer.msg("上传失败，请重新上传")
                }
            });
        });
    // before: function uploadFile() {
    //     this.data = {
    //         test: $('input[name="test"]').val()
    //     }
    // }

    //搜索功能
    $("#search").on("click", function () {
        // var data = form.val("search");
        var data = $("#searchInput").val();
        // console.log(data)
        option.where.keyWord = data
        table.reload("demo", option)
    })

    //列表操作：编辑与删除
    table.on('tool(demo)', function (obj) {
        var layEvent = obj.event,
            data1 = obj.data;

        if (layEvent === 'edit') {
            // console.log(data1)
            // $("#changeDate").val(data)
            $("#editCaseDuty").val(data1.caseDuty);
            //	$("#editCommunityDuty").val(data1.communityDuty);
            $(".editChangeDate").val(data1.workingDate)
            layer.open({
                type: 1,
                title: '编辑',
                content: $('#editTableDuty'),
                area: ['421px', '260px'],
                btn: ['确认修改', '取消'],
                yes: function (index, layero) {
                    var editDate = $("#editDate").val();
                    var editCaseDuty = $("#editCaseDuty").val();
                    //	var editCommunityDuty = $("#editCommunityDuty").val();
                    var data2 = {}
                    data2.workingDate = editDate;
                    data2.caseDuty = editCaseDuty;
                    //	data2.communityDuty = editCommunityDuty;
                    data2.id = data1.id;
                    // console.log(data2)
                    $.ajax({
                        url: url + "/document​/deletebyuserid",
                        method: "post",
                        data: data2,
                        headers: {
                            token: localStorage.getItem('token')
                        },
                        success: function (data) {
                            // console.log(data)
                            if (data.code === 1) {
                                layer.closeAll();
                                tableIns.reload();
                                layer.msg("修改成功！")
                            } else {
                                layer.msg(data.msg)
                            }
                        }

                    })
                }
            })
        } else {
            layer.confirm('确定删除此行内容？', {
                btn: ['确定', '取消']
            }, function () {
                // console.log("确定")
                console.log(data1);
                $.ajax({
                    url: url + "/dutyroster/deletedutyroster?ids=" + data1.id,
                    method: "post",
                    headers: {
                        token: localStorage.getItem('token')
                    },
                    success: function (data) {
                        console.log(data)
                        if (data.code === 1) {
                            tableIns.reload();
                            layer.msg('删除成功！')

                        } else {
                            layer.msg(data.message)
                        }

                    },
                    error: function (err) {
                        layer.msg('删除失败！')
                    }
                })
            }, function () {
                console.log("取消")
            })
        }
    })


});
